package org.example.leetcode.gateway.filter;


import org.example.leetcode.common.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Value("${whitePath}")
    String whitePath;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        PathMatcher pathMatcher=new AntPathMatcher();
        String[] split = whitePath.split(",");
        boolean f=false;
        for(String s:split){
            String path = exchange.getRequest().getURI().getPath();
            if(pathMatcher.match(s,path)){
                f=true;
            }
        }
        if(!f){
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if(!StringUtils.hasText(token)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            setResponseHead(exchange);
            return exchange.getResponse().setComplete();
        }
        boolean b;
        try {
            b = TokenUtils.validToken(token);
        }catch (Exception e){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            setResponseHead(exchange);
            return exchange.getResponse().setComplete();        }
        if(!b){
            //这里如果过期，前端应该去调用refreshToken，来获取新token，如果refreshToken都失效，那么就重新登录
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            setResponseHead(exchange);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
    private void setResponseHead(ServerWebExchange exchange){
//        exchange.getResponse().getHeaders().set("Access-Control-Allow-Origin", "*");
//        exchange.getResponse().getHeaders().set("Access-Control-Allow-Credentials", "true");
    }
}
